package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Bed;
import com.zzyl.nursing.domain.CheckInConfig;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.BedMapper;
import com.zzyl.nursing.mapper.CheckInConfigMapper;
import com.zzyl.nursing.mapper.ContractMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author qqq
 * @date 2024-12-28
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //1.校验老人是否已入住 （通过老人身份证号码, status in (1,2,3,4)）
        Elder elder = getElder(dto.getCheckInElderDto().getIdCardNo());
        //2.老人已入住，则要终止业务
        if (null != elder) {
            throw new ServiceException("老人已入住了!");
        }
        //3.更新床位状态为已入住，防止并发问题
        // 先查再更新
        // 通过床位id查询
        // status=0  update bed set status=1 where id=? and status=0  affected row:0 更新，1：更新成功
        // 更新状态
        updateBedStatus(dto.getCheckInConfigDto().getBedId());
        //4.新增或更新老人
        Elder elderInDB = insertOrUpdateElder(dto.getCheckInElderDto(), dto.getCheckInConfigDto().getBedId());
        //5.新增签约办理
        insertContract(dto, elderInDB);
        //6.新增入住信息
        CheckIn checkIn = insertCheckIn(dto, elderInDB);
        //7.新增入住配置
        insertCheckInConfig(checkIn.getId(), dto.getCheckInConfigDto());
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        //查询入住信息表
        CheckIn checkIn = getById(id);
        //老人信息 elder, elder_id
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        CheckInElderVo elderVo = BeanUtil.toBean(elder, CheckInElderVo.class);

        // 获取老人的年龄
        int age = IdcardUtil.getAgeByIdCard(elder.getIdCardNo());
        elderVo.setAge(age);
        vo.setCheckInElderVo(elderVo);

        //家属信息,在哪check_in.remark字段,json字符串
        String jsonString = checkIn.getRemark();
        //解析了json字符串得到了家属对象集合
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(jsonString, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVoList);

        //入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));
        //转成CheckInConfigVo
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);

        //设置座位编号
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        vo.setCheckInConfigVo(checkInConfigVo);

        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elderId));
        vo.setContract(contract);
        return vo;
    }

    private void insertContract(CheckInApplyDto dto, Elder elderInDB) {
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        //设置合同编号
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        // 设置老人ID与老人的名称
        contract.setElderId(elderInDB.getId().intValue());
        contract.setElderName(elderInDB.getName());
        //开始时间与结束时间
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        //设置状态
        contract.setStatus(0);// 未生效
        if (contract.getStartDate().isBefore(LocalDateTime.now())) {
            contract.setStatus(1);// 已生效
        }
        contractMapper.insert(contract);
    }

    /**
     * 添加入住配置信息
     *
     * @param id
     * @param checkInConfigDto
     */
    private void insertCheckInConfig(Long id, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 添加入住信息
     *
     * @param dto
     * @param elderInDB
     */
    private CheckIn insertCheckIn(CheckInApplyDto dto, Elder elderInDB) {
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setIdCardNo(elderInDB.getIdCardNo());
        checkIn.setElderId(elderInDB.getId());
        checkIn.setBedNumber(elderInDB.getBedNumber());
        checkIn.setElderName(elderInDB.getName());
        checkIn.setStatus(0);//已入住
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        // MP的保存方法
        save(checkIn);
        return checkIn;
    }


    /**
     * 新增签约办理
     * @param dto
     */


    /**
     * 新增或更新老人信息
     *
     * @param checkInElderDto
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Long bedId) {
        //判断 老人是否存在
        // 通过身份证号码查询
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 通过身份证号码查询
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        Elder elderInDB = elderMapper.selectOne(lambdaQueryWrapper);
        // 查询床位信息
        Bed bed = bedMapper.selectById(bedId);
        // 构建老人信息
        Elder elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());

        // 不存在则新增
        if (null == elderInDB) {
            elderMapper.insert(elder);
        } else {
            // 通过id更新
            elder.setId(elderInDB.getId());
            // 存在则更新
            elderMapper.updateById(elder);
        }
        return elder;
    }

    /**
     * 更新床位状态为已入住，防止并发问题
     *
     * @param bedId
     */
    private void updateBedStatus(Long bedId) {
        LambdaUpdateWrapper<Bed> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(Bed::getBedStatus, 1)
                .eq(Bed::getId, bedId).eq(Bed::getBedStatus, 0);
        // 受影响的行数，更新了几条记录
        int affectedRows = bedMapper.update(null, lambdaUpdateWrapper);
        if (affectedRows == 0) {
            // 更新失败了
            throw new ServiceException("所选床位已经被使用了，请选择其它床位!");
        }
    }

    /**
     * 校验老人是否已入住 （通过老人身份证号码, status in (1,2,3,4)）
     *
     * @return
     */
    private Elder getElder(String idCardNo) {
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构建status 1，2，3，4都是代表老人已入住
        lambdaQueryWrapper.in(Elder::getStatus, List.of(1, 2, 3, 4))
                // 通过身份证号码查询
                .eq(Elder::getIdCardNo, idCardNo);
        return elderMapper.selectOne(lambdaQueryWrapper);
    }
}
